package com.maomao.template.service.impl;

import com.maomao.template.bean.User;
import com.maomao.template.dao.UserDao;
import com.maomao.template.dao.mapper.UserMapper;
import com.maomao.template.manager.UserManager;
import com.maomao.template.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @author admin
 * @date 2018/4/11
 */
@Service
public class UserServiceImpl implements UserService {

    private  static final Logger logger= LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void create(String name, Integer age) {
        userDao.create(name,age);
    }

    @Override
    public void deleteByName(String name) {
        userDao.deleteByName(name);
    }

    @Override
    public Integer getAllUsers() {
        return userDao.getAllUsers();
    }

    @Override
    public void deleteAllUsers() {
        userDao.deleteAllUsers();
    }

    @Override
    public List<User> selectAllUsers() {
        return userDao.selectAllUsers();
    }

    @Override
    public User selectUserById(int id) {
        String key="user_"+id;
        ValueOperations<String,User> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            User user = operations.get(key);
            logger.info("find user from redis :"+user);
            return user;
        }
        User user = userDao.selectUserById(id);
        operations.set(key,user);
        logger.info("find user from DB :"+user);

        return user;
    }

    @Override
    public void reloadUsers() {
        List<User> users=userDao.selectAllUsers();;
        UserManager.initUsers(users);
    }
}
